package list

import (
	"sync"
)

type Source struct {
	Address string
	Pid     int
	Count   int
}

type PlayList struct {
	List map[string]Source
	Lock sync.Mutex
}

func NewPlayList() (p PlayList) {
	p.List = make(map[string]Source)
	return
}

func (p *PlayList) Add(name string, s Source) {
	//因为要开启这个资源，所有开启数量已经为1了
	s.Count = 1

	p.Lock.Lock()
	defer p.Lock.Unlock()

	v, ok := p.List[name]
	if ok {
		v.Count += 1
		p.List[name] = v
	} else {
		p.List[name] = s
	}
}

func (p *PlayList) Remove(name string) (c int) {
	p.Lock.Lock()
	defer p.Lock.Unlock()

	v, ok := p.List[name]
	if ok {
		if v.Count > 1 {
			v.Count--
			p.List[name] = v
			c = v.Count
			return
		} else {
			delete(p.List, name)
		}
	}
	c = 0
	return
}

func (p *PlayList) Get(name string) (s Source) {
	p.Lock.Lock()
	defer p.Lock.Unlock()

	v, ok := p.List[name]
	if ok {
		s = v
	}
	return
}

func (p *PlayList) IsHave(name string) bool {
	p.Lock.Lock()
	defer p.Lock.Unlock()

	_, ok := p.List[name]
	return ok
}
